<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-11-25
 * Time: 下午 4:03
 */

defined('ByShopWWI') or exit('Access Invalid!');

class loginControl extends mobileMemberControl {

    public function __construct(){
        parent::__construct();
    }

    public function indexOp(){
        //跳转的页面
        if(empty($_GET['ref_url'])){
            $ref_url = getReferer();
        }else {
            $ref_url = $_GET['ref_url'];
        }
        //echo '<h1>'.$ref_url.'</h1>';exit;
      //  Tpl::output('ref_url',  $ref_url);
      //  Tpl::showpage('login');
     if(!empty($_SESSION['is_login'])){
       	redirect('index.php?act=member');
     }else{
         $user_agent = $_SERVER['HTTP_USER_AGENT'];
         if (strpos($user_agent, 'MicroMessenger') === false) {
             Tpl::showpage('login');return;
         }
        include_once(BASE_ROOT_PATH.'/app/api/Weixin.class.php');
        $c = new Weixin();
        $c->getOpenId();
        $info = $c->getSNSUserInfo();
        //查找会员记录,如果没有则插入一个
        $model_member = Model('member');
        $array = array();
        $array['weixin_unionid']   = $info['openid'];
        
        $url = $info['headimgurl'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0); // 设置是否显示header信息 0是不显示，1是显示 默认为0
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据，而不是直接输出
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar); //发送cookie文件
        $img = curl_exec($ch); //发送HTTP请求
        file_put_contents(BASE_ROOT_PATH.'/data/upload/'.ATTACH_AVATAR.'/avatar_'.$info['openid'].'.jpg', $img);

        $member_info = $model_member->getMemberInfo($array);
        if(empty($member_info) && $info['openid']) {
            $member = array();
            $member['weixin_unionid']   = $info['openid'];
            $member['weinxin_info'] = serialize($info);
            $member['member_name'] = 'jg'.uniqid();
            $member['member_nickname'] = $info['nickname'];
            $member['member_avatar'] = 'avatar_'.$info['openid'].'.jpg';
            $member['member_passwd'] = '';
            $member['member_email'] = '';
            $result = $model_member->addMember($member);
            if($result){
              //save headimg
            }
          $member_info = $model_member->getMemberInfo($array);
        }
        $_POST['client'] = 'wap';
        if(!empty($member_info)) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if($token) {
                $_SESSION['is_login'] = '1';
                $_SESSION['member_id'] = $member_info['member_id'];
                $_SESSION['openid'] = $member_info['weixin_unionid'];
				$_SESSION['member_name'] = $member_info['member_name'];
				$_SESSION['is_buy'] = $member_info['is_buy'];

                $seller_info = Model('seller')->getSellerInfo(array('seller_name' => $member_info['member_name']));
                if($seller_info) {
                    $_SESSION['store_id'] = intval($seller_info['store_id']);
                }
               	redirect('index.php?act=member');
            } else {
                output_error('登录失败');
            }
        } 
       
     }
    }

    /**
     * 登录
     *
     */
     
    public function loginOp(){
        if(empty($_POST['username']) || empty($_POST['password']) || !in_array($_POST['client'], $this->client_type_array)) {
            output_error('登录失败');
        }

        $model_member = Model('member');

        $array = array();
        $array['member_name']   = $_POST['username'];
        $array['member_passwd'] = md5($_POST['password']);
        //跳转的页面
        $ref_url = $_POST['ref_url'];
        //echo $ref_url;exit;
        $member_info = $model_member->getMemberInfo($array);
        if(empty($member_info) && preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $_POST['username'])) {//根据会员名没找到时查手机号
            $array = array();
            $array['member_mobile']   = $_POST['username'];
            $array['member_passwd'] = md5($_POST['password']);
            $member_info = $model_member->getMemberInfo($array);
        }
        if(empty($member_info) && (strpos($_POST['username'], '@') > 0)) {//按邮箱和密码查询会员
            $array = array();
            $array['member_email']   = $_POST['username'];
            $array['member_passwd'] = md5($_POST['password']);
            $member_info = $model_member->getMemberInfo($array);
        }

        if(!empty($member_info)) {
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);
            if($token) {
                $_SESSION['is_login'] = '1';
                $_SESSION['member_id'] = $member_info['member_id'];
				$_SESSION['member_name'] = $member_info['member_name'];
				$_SESSION['is_buy'] = $member_info['is_buy'];

                $seller_info = Model('seller')->getSellerInfo(array('seller_name' => $_POST['username']));
                if($seller_info) {
                    $_SESSION['store_id'] = intval($seller_info['store_id']);
                }
                output_data(array('username' => $member_info['member_name'], 'userid' => $member_info['member_id'], 'key' => $token,'ref_url'=>$ref_url));
            } else {
                output_error('登录失败');
            }
        } else {
            output_error('用户名密码错误');
        }
    }
   
    /**
     * 登录生成token
     */
    private function _get_token($member_id, $member_name, $client) {
        $model_mb_user_token = Model('mb_user_token');

        //重新登录后以前的令牌失效
        //暂时停用
        //$condition = array();
        //$condition['member_id'] = $member_id;
        //$condition['client_type'] = $client;
        //$model_mb_user_token->delMbUserToken($condition);

        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0,999999)));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['token'] = $token;
        $mb_user_token_info['login_time'] = TIMESTAMP;
        $mb_user_token_info['client_type'] = $client;

        $result = $model_mb_user_token->addMbUserToken($mb_user_token_info);

        if($result) {
            return $token;
        } else {
            return null;
        }

    }
	

    
    
    public function registerOp(){
        $model_member = Model('member');
        $phone = $_POST['username'];
        $captcha = $_POST['sms_code'];
        if (!empty($phone) && strlen($phone) == 11 && strlen($captcha) == 6){
            if(C('sms_register') != 1) {
                showDialog('系统没有开启手机注册功能','','error');
            }
           
            $member = $model_member->getMemberInfo(array('member_mobile'=> $phone));//检查手机号是否已被注册
            if(!empty($member)) {
                output_error('手机号已被注册');
            }
           if (strlen($phone) == 11 && strlen($captcha) == 6){
            $condition = array();
            $condition['log_phone'] = $phone;
            $condition['log_captcha'] = $captcha;
            $condition['log_type'] = 1;
            $model_sms_log = Model('sms_log');
            $sms_log = $model_sms_log->getSmsInfo($condition);
            if(empty($sms_log) || ($sms_log['add_time'] < TIMESTAMP-1800)) {//半小时内进行验证为有效
                output_error('动态码错误或已过期，重新输入');
            }
           }

            $member = array();
            $member_name = $phone;
            $member['member_name'] = $member_name;
            $member['member_passwd'] = $_POST['password'];
            $member['member_email'] = '';
            $member['member_mobile'] = $phone;
            $member['member_mobile_bind'] = 1;
            $result = $model_member->addMember($member);
            if($result) {
                $member = $model_member->getMemberInfo(array('member_mobile'=> $phone));
                $model_member->createSession($member,true);//自动登录
                $token = $this->_get_token($member['member_id'], $member['member_name'], $_POST['client']);
               if($token) {
                $_SESSION['is_login'] = '1';
                $_SESSION['member_id'] = $member['member_id'];
				$_SESSION['is_buy'] = $member_info['is_buy'];

                 $seller_info = Model('seller')->getSellerInfo(array('seller_name' => $member_name));
                 if($seller_info) {
                       $_SESSION['store_id'] = intval($seller_info['store_id']);
                 }

                   if(!empty($_POST['rg'])){   //注册邀请积分  hyy
                       $invite_model= Model('member');
                       $set_code=array();
                       $get_code=array();
                       $get_code['code'] = $_POST['rg'];
                       if($invite_model->selectCode($get_code)){

                           $set_code['user']= $_SESSION['member_name'];
                           $set_code['code']= $_SESSION['member_id'];
                           $set_code['guest']= $_POST['rg'];
                           $set_code['invite_time']= time();
                           $invite=$invite_model->inviteCode($set_code);

                           if($invite){ //邀请成功后，邀请人加积分
                               $points_model = Model('points');
                               $member_model = Model('member');
                               $mem_name = $member_model->getMemberInfoByID($_POST['rg'], '*');
                               $condition['pl_memberid'] = $_POST['rg'];
                               $condition['pl_membername'] = $mem_name['member_name'];
                               $condition['pl_points'] = 20;

                               $points_model->savePointsLog('invite',$condition,true);
                           }


                       }
                   }else{
                       $invite_model= Model('member');
                       $set_code['user']= $_SESSION['member_name'];
                       $set_code['code']= $_SESSION['member_id'];
                       $set_code['invite_time']= time();
                       $invite_model->inviteCode($set_code);
                   }


                output_data(array('username' => $member['member_name'], 'userid' => $member['member_id'], 'key' => $token));
               } else {
                output_error('注册失败');
              }
           
        }
      }
    }
    
/**
     * 短信动态码
     */
    public function get_captchaOp(){
        $state = '发送失败';
        $phone = $_GET['phone'];
        if (strlen($phone) == 11){
        	//检查是否为已注册用户
            $log_type = $_GET['type'];//短信类型:1为注册,2为登录,3为找回密码
            if($log_type==1){
            	$model_member = Model('member');
            	$member = $model_member->getMemberInfo(array('member_mobile'=> $phone));//检查手机号是否已被注册
            	if(!empty($member)) {
            		exit('手机号已被使用');
            	}
            }
            
            $model_sms_log = Model('sms_log');
            $condition = array();
            $condition['log_ip'] = getIp();
            $condition['log_type'] = $log_type;
            $sms_log = $model_sms_log->getSmsInfo($condition);
            if(!empty($sms_log) && ($sms_log['add_time'] > TIMESTAMP-60)) {//同一IP十分钟内只能发一条短信
                $state = '同一IP地址一分钟内，请勿多次获取动态码！';
            } else {
                $state = 'true';
                $log_array = array();
                $model_member = Model('member');
                $member = $model_member->getMemberInfo(array('member_mobile'=> $phone));
                $captcha = rand(100000, 999999);
                $log_msg = '【'.C('site_name').'】您于'.date("Y-m-d");
                switch ($log_type) {
                    case '1':
                        if(C('sms_register') != 1) {
                            $state = '系统没有开启手机注册功能';
                        }
                        if(!empty($member)) {//检查手机号是否已被注册
                            $state = '当前手机号已被注册，请更换其他号码。';
                        }
                        $log_msg .= '申请注册会员，动态码：'.$captcha.'。';
                        break;
                    case '2':
                    	if(!empty($_GET['member_id'])){
                    		$model_member = Model('member');
                    		$member = $model_member->getMemberInfo(array('member_mobile'=> $phone,'member_id'=>array('neq',(int)$_GET['member_id'])));//检查手机号是否已被注册
                    		if(!empty($member)) {
                    			$state ='手机号已被使用';
                    		}
                    	}
                    	$log_msg .= '申请绑定手机号，动态码：'.$captcha.'。';
                    	$log_array['member_id'] = $member['member_id'];
                    	$log_array['member_name'] = $member['member_name'];
                    	break;
                    case '3':
                        if(C('sms_password') != 1) {
                            $state = '系统没有开启手机找回密码功能';
                        }
                        if(empty($member)) {//检查手机号是否已绑定会员
                            $state = '当前手机号未注册，请检查号码是否正确。';
                        }
                        $log_msg .= '申请重置登录密码，动态码：'.$captcha.'。';
                        $log_array['member_id'] = $member['member_id'];
                        $log_array['member_name'] = $member['member_name'];
                        break;
                    default:
                        $state = '参数错误';
                        break;
                }
                if($state == 'true'){
                    $sms = new Sms();
                    $result = $sms->send($phone,$log_msg);
                   // echo $log_msg;$result = true;
                    if($result){
                        $log_array['log_phone'] = $phone;
                        $log_array['log_captcha'] = $captcha;
                        $log_array['log_ip'] = getIp();
                        $log_array['log_msg'] = $log_msg;
                        $log_array['log_type'] = $log_type;
                        $log_array['add_time'] = time();
                        $model_sms_log->addSms($log_array);
                    } else {
                        $state = '手机短信发送失败';
                    }
                }
            }
        } else {
            $state = '验证码错误';
        }
        exit($state);
    }
    
    public function logoutOp(){
        Language::read("home_login_index");
        $lang   = Language::getLangContent();

        // 清理COOKIE
        $model_member = Model('member');
        $member_info = $model_member->getMemberInfo(array('member_id'=>$_SESSION['member_id']));
        $model_mb_user_token = Model('mb_user_token');
        //获取12小时以内的token
        $condition = array();
        $condition['member_id'] = $member_info['member_id'];
        $condition['member_name'] = $member_info['member_name'];
        $condition['client_type'] = $_GET['client'];
        $model_mb_user_token->delMbUserToken($condition);
        
        setNcCookie('msgnewnum'.$_SESSION['member_id'],'',-3600);
        setNcCookie('auto_login', '', -3600);
        setNcCookie('cart_goods_num','',-3600);
        session_unset();
        session_destroy();
				/**
		* 同步登录通知
		*/
		if(C('ucenter_status')) {
			/**
			* Ucenter处理
			*/
			$model_ucenter = Model('ucenter');
			$out_str = $model_ucenter->userLogout();
			$lang['login_logout_success'] = $lang['login_logout_success'].$out_str;	
			if(empty($_GET['ref_url'])){
				$ref_url = getReferer();
			}else {
				$ref_url = $_GET['ref_url'];
			}
			showMessage($lang['login_logout_success'],'index.php?act=login&ref_url='.urlencode($ref_url));			
		}else{
			redirect();
		}
    }
    
    public function findpasswordOp(){
        Tpl::showpage('findpassword');
    } 
    
    public function check_captchaOp(){
    	  $phone = $_POST['phone'];
    	  $captcha = $_POST['captcha'];
    	  $type = $_POST['type'];
         if (strlen($phone) == 11 && strlen($captcha) == 6){
            $condition = array();
            $condition['log_phone'] = $phone;
            $condition['log_captcha'] = $captcha;
            $condition['log_type'] = $type;
            $model_sms_log = Model('sms_log');
            $sms_log = $model_sms_log->getSmsInfo($condition);
 
           if(empty($sms_log) || ($sms_log['add_time'] < TIMESTAMP-1800)) {//半小时内进行验证为有效
                output_error('动态码错误或已过期，重新输入');
            }else{
            	output_data(true);
            }
           }else{
             output_error('格式不正确');
           }
           
    }
    
       
    public function resetpasswordOp(){
    	 $phone = $_GET['phone'];
    	 $captcha = $_GET['captcha'];
    	 $type = $_GET['type'];
    	 $condition = array();
         $condition['log_phone'] = $phone;
         $condition['log_captcha'] = $captcha;
         $condition['log_type'] = $type;
         $model_sms_log = Model('sms_log');
         $sms_log = $model_sms_log->getSmsInfo($condition);
         if(empty($sms_log)){
         	showMessage('动态码错误或已过期，重新输入','index.php?act=login&op=findpassword');
         }else{
         	Tpl::output('phone',$phone);
         	Tpl::output('captcha',$captcha);
         	Tpl::output('type',$type);
    	    Tpl::showpage('resetpassword');
         }
    }
    
    public function resetpasswordvalOp(){
    	//检查动态码
    	 $phone = $_POST['phone'];
    	 $captcha = $_POST['captcha'];
    	 $type = $_POST['type'];
    	 $condition = array();
         $condition['log_phone'] = $phone;
         $condition['log_captcha'] = $captcha;
         $condition['log_type'] = $type;
         $model_sms_log = Model('sms_log');
         $sms_log = $model_sms_log->getSmsInfo($condition);
         //动态码正确时修改密码
         if(!empty($sms_log)){
            $model_member = Model('member');
            $result = $model_member->editMember(array('member_id'=>(int)$sms_log['member_id']),array('member_passwd'=>md5(trim($_POST['password']))));
            if($result){
            	output_data($result);
            }else{
            	output_error('密码更新错误');
            }
         }
    }
    
    public function emailcaptchaOp(){
    	if(!empty($_GET['email'])){
    	  if(!empty($_GET['member_id'])){
    	  	$model_member = Model('member');
    	  	$member = $model_member->getMemberInfo(array('member_email'=> trim($_GET['email']),'member_id'=>array('neq',(int)$_GET['member_id'])));//检查手机号是否已被注册
    	  	if(!empty($member)) {
    	  		exit('邮箱已被使用');
    	  	}
    	  }
    	  $captcha = rand(100000, 999999);
    	  $email	= new Email();
    	  $subject = '绑定邮箱动态码';
    	  $message  = '【'.C('site_name').'】您于'.date("Y-m-d");
    	  $message .= '申请绑定邮箱，动态码：'.$captcha.'。';
    	  $_SESSION['mail_captcha'] = $captcha;
		  $result	= $email->send_sys_email($_GET["email"],$subject,$message);
		  exit('动态码发送成功');
    	}
    }

    //init签到页面
    public function signOp(){
        $condition_arr = array();
        $condition_arr['pl_memberid'] = $_SESSION['member_id'];
        $condition_arr['pl_stage'] = 'sign';

        $points_model = Model('points');
        $list_points = $points_model->getPointsLogList($condition_arr);

        $condition_arr['pl_addtime'] = trim(date('Y-m-d'));
        $log_array = $points_model->getPointsInfo($condition_arr);
        $sign_today = 0;
        if (!empty($log_array)){
            $sign_today = 1;
        }

        $point_count = 0;
        $point_num = 0;
        $time = $sign_today==true ? time() : (time()- ( 1  *  24  *  60  *  60 ));
        foreach ($list_points as $k=>$v){
            $point_count += $v['pl_points'];
            if(date("Y-m-d",$v['pl_addtime'])==date("Y-m-d",$time)){
                $point_num += 1;
                $time = $time - ( 1  *  24  *  60  *  60 );
            }else{
                break;
            }
        }

        Tpl::output('point_count',$point_count);//签到总积分
        Tpl::output('sign_today',$sign_today);//今日是否已签到
        Tpl::output('point_num',$point_num);//连续签到天数

        Tpl::showpage('sign');
    }

    public function save_signOp(){//ajax签到
        $points_model = Model('points');
        $points_model->savePointsLog('sign',array('pl_memberid'=>$_SESSION['member_id'],'pl_membername'=>$_SESSION['member_name']),true);
        echo '1';
    }

    public function sign_recordOp(){//签到记录
        $condition_arr = array();
        $condition_arr['pl_memberid'] = $_SESSION['member_id'];
        $condition_arr['pl_stage'] = 'sign';

        //分页
//        $page   = new Page();
//        $page->setEachNum(10);
//        $page->setStyle('admin');
        //查询积分日志列表
        $points_model = Model('points');
        $list_log = $points_model->getPointsLogList($condition_arr);
        Tpl::output('list_log',$list_log);

        Tpl::showpage('sign_record');
    }

    public function sign_ruleOp(){//签到规则
        Tpl::showpage('sign_rule');
    }
    
}
